﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TruongVu.Business;
using TruongVu.Data;

namespace TruongVuWebsite.Admin
{
    public partial class Decree : System.Web.UI.Page
    {
        private DocumentModel _documentModel = new DocumentModel();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack)
            {
                return;
            }

            if (Request["ID"] != null)
            {
                int id = -1;
                if (int.TryParse(Request["ID"], out id))
                {
                    Document document = this._documentModel.Get(id);
                    if (document != null)
                    {
                        this.NameTextBox.Text = document.Tittle;
                        this.CurrentFileTextBox.Text = document.Content;
                    }
                }
            }
        }

        protected void UploadButton_Click(object sender, EventArgs e)
        {
            if (FileUploadControl.HasFile)
            {
                if (FileUploadControl.PostedFile.ContentLength > 5000000)
                {
                    this.DisplayMessage(this, "Kích thướt file quá lớn.");
                    return;
                }

                string filename = System.IO.Path.GetFileName(FileUploadControl.FileName);
                FileUploadControl.SaveAs(Server.MapPath("~/Documents/") + filename);
                this.CurrentFileTextBox.Text = "~/Documents/" + filename;
            }
        }

        protected void SubmitButton_Click(object sender, ImageClickEventArgs e)
        {
            Document document = new Document();
            if (Request["ID"] != null)
            {
                int id = -1;
                if (int.TryParse(Request["ID"], out id))
                {
                    document.ID = id;
                }
            }

            document.Tittle = this.NameTextBox.Text;
            document.Content = this.CurrentFileTextBox.Text;

            if (Request["ID"] != null)
            {
                this._documentModel.Update(document);
            }
            else
            {
                this._documentModel.Insert(document);
            }

            Response.Redirect("DecreeManagement.aspx");
        }

        private void DisplayMessage(Control page, string msg)
        {
            string myScript = String.Format("alert('{0}');", msg);

            ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);
        }
    }
}